package juc

import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

fun main() = runBlocking {
    var count = 0
    val mutex = Mutex() // 协程互斥锁
    val coroutineCount = 5
    val incrementPerCoroutine = 12

    repeat(coroutineCount) {
        launch(Dispatchers.Default) {
            repeat(incrementPerCoroutine) {
                mutex.withLock { // 协程锁，自动释放
                    count++
                }
            }
        }
    }

    delay(1000)
    println("最终结果：$count（预期：${coroutineCount * incrementPerCoroutine}）")
}